package org.moon.framework.autoconfigure.oss.impl;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.moon.framework.autoconfigure.config.SpringContextConfig;
import org.moon.framework.autoconfigure.oss.OssService;
import org.moon.framework.autoconfigure.oss.OssTemplate;
import org.moon.framework.autoconfigure.oss.props.OssProperties;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 基于 DB 存储的文件客户端的配置类
 * @author 村口的大爷
 */
@Slf4j
public class DBOssService implements OssService {

    private OssProperties ossProperties;

    public DBOssService(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
    }


    @Override
    public String upload(byte[] content, String originalName) {
        String path = getFilePath(ossProperties.getBasePath(),originalName);
        path = StrUtil.replace(path, StrUtil.BACKSLASH, StrUtil.SLASH);
        String link = formatFileUrl(ossProperties.getDomain(),ossProperties.getId(), path);
        insert(ossProperties.getId(),originalName,link, content, OssTemplate.FileStorageEnum.DB);
        return link;
    }

    @Override
    public void delete(String link) {
        delete(ossProperties.getId(), link);
    }

    @Override
    public void batchDelete(List<String> links) {
        for(String link:links){
            delete(ossProperties.getId(), link);
        }
    }

    @Override
    public byte[] getContent(String link) {
        return selectContent(ossProperties.getId(), link);
    }

    /**
     * 获得文件内容
     *
     * @param configId 配置编号
     * @param link 路径
     * @return 内容
     */
    private byte[] selectContent(Integer configId, String link){
        JdbcTemplate jdbcTemplate = SpringContextConfig.getBean(JdbcTemplate.class);
        String sql = "select content from "+ OssTemplate.DB_OSS_TABLE_NAME + " where config_id=" + configId + " and link='" + link+"'";
        List<byte[]> contents = jdbcTemplate.query(sql,new RowMapper<byte[]>(){
            @Override
            public byte[] mapRow(ResultSet rs, int i) throws SQLException {
                return blobToByte(rs.getBlob("content"));
            }
        });
        if(contents==null ||contents.size()==0){
            return null;
        }
        return contents.get(0);
    }

    private byte[] blobToByte(Blob blob){
        byte[] bytes = null;
        try (BufferedInputStream inBuffered = new BufferedInputStream(blob.getBinaryStream());){
            ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
            byte[] temp = new byte[1024];
            int size = 0;
            while ((size = inBuffered.read(temp)) != -1) {
                out.write(temp, 0, size);
            }
            bytes = out.toByteArray();
        } catch (Exception ex) {
            log.error(ex.getMessage(),ex);
        }
        return bytes;
    }
}